﻿const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();

// 设置安灯系统端口（使用不同的端口）
const PORT = process.env.ANDON_PORT || 3002;

// 中间件
app.use(cors());
app.use(bodyParser.json());

// 记录请求的简单中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 初始化数据库
const db = require("./db/database");

// 导入路由
const eventRoutes = require("./routes/eventRoutes");
const historyRoutes = require("./routes/historyRoutes");

// 使用路由
app.use("/api/events", eventRoutes);
app.use("/api/history", historyRoutes);

// 欢迎页面
app.get("/", (req, res) => {
  res.json({
    service: " 安灯系统服务",
    port: PORT,
    status: "运行中",
    endpoints: [
      "GET /api/events - 获取事件列表",
      "GET /api/history - 获取历史记录", 
      "GET /health - 健康检查"
    ],
    timestamp: new Date().toISOString()
  });
});

// 健康检查端点
app.get("/health", (req, res) => {
  res.json({ status: "OK", timestamp: new Date().toISOString() });
});

// 初始化MQTT（如果存在）
let mqttClient = null;
try {
  mqttClient = require("./mqtt/mqttClient");
  console.log(" MQTT客户端已初始化");
} catch (error) {
  console.log("  MQTT模块未找到，继续无MQTT模式");
}

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error("服务器错误:", err.stack);
  res.status(500).json({ 
    error: "服务器内部错误",
    message: err.message 
  });
});

// 404处理
app.use((req, res) => {
  res.status(404).json({ error: "端点未找到" });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(` 安灯系统服务器运行在端口 ${PORT}`);
  console.log(` API地址: http://localhost:${PORT}/api`);
  
  // 开发环境下添加测试数据
  if (process.env.NODE_ENV !== "production") {
    console.log(" 开发模式: 添加测试数据");
    addTestData();
  }
});

// 添加测试数据的函数
function addTestData() {
  const Event = require("./models/Event");
  
  // 清空现有数据
  db.run("DELETE FROM events", () => {
    console.log(" 已清空测试数据");
    
    // 添加测试事件
    const testEvents = [
      { title: "机器故障", description: "生产线A的机器停止运行", severity: "high" },
      { title: "材料短缺", description: "缺少零件B-123", severity: "medium" },
      { title: "安全警报", description: "区域C检测到烟雾", severity: "critical" },
      { title: "网络中断", description: "东区路由器离线", severity: "medium" },
      { title: "温度异常", description: "反应釜温度超过阈值", severity: "high" }
    ];
    
    let completed = 0;
    testEvents.forEach((event, index) => {
      Event.create(event.title, event.description, event.severity)
        .then(id => {
          console.log(` 创建测试事件: ${event.title} (ID: ${id})`);
          completed++;
          
          if (completed === testEvents.length) {
            console.log(" 所有测试数据添加完成");
          }
        })
        .catch(err => {
          console.error(` 创建测试事件失败: ${event.title}`, err);
        });
    });
  });
}

module.exports = app;
